<template>
  <div>
    <el-card style="margin: 3.5px 0 0 0">
      <vxe-grid
        ref="xGrid"
        v-bind="gridOptionsList"
        @checkbox-change="checkboxChange"
        @checkbox-all="selectAllCheckboxChange"
      >
        <template #toolbar_buttons>
          <buttonList :buttonArr="buttonArr"></buttonList>
        </template>
      </vxe-grid>
    </el-card>
    <!-- 高级查询模态框 -->
    <el-dialog
      v-model="dialogVisible"
      title="列自定义弹框"
      width="65%"
      draggable
      class="unity_advancedQueryDialog"
    >
      <el-alert
        title="提示"
        type="success"
        description="初始化状态下个人列自定义跟随系统设置；个人列自定义与系统设置不同时取个人设置。重置个人设置可重新跟随系统设置。"
        show-icon
        style="margin-bottom: 10px"
      />
      <vxe-grid ref="customGrid" v-bind="customColumnConfig.config">
        <template #whetherToHide="{ row }">
          <el-switch v-model="row.exhibition" />
        </template>

        <template #dragBtn>
          <span class="drag-btn">
            <el-icon><Menu /></el-icon>
          </span>
        </template>
        <template #dragTip>
          <vxe-tooltip
            v-model="showHelpTip"
            content="按住后可以上下拖动排序"
            enterable
          >
            <i
              class="vxe-icon-question-circle-fill"
              @click="showHelpTip = !showHelpTip"
            ></i>
          </vxe-tooltip>
        </template>
      </vxe-grid>

      <template #footer>
        <div class="dialog-footer-advanced">
          <el-button>重置</el-button>
          <el-button>取消</el-button>
          <el-button type="primary" @click="saveCustomColumn"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  DefineComponent,
  onUnmounted,
  nextTick,
} from "vue";
import { Menu } from "@element-plus/icons-vue";
import { VxeGridProps } from "vxe-table";
import buttonList from "./modules/buttonList.vue";
import { ButtonType, ElMessage } from "element-plus";
import Sortable from "sortablejs";
// 引入自定义请求库
import { postAction, getAction } from "@/utils/system/commonUse";

// 传过来按钮详情
interface buttonArrDetails {
  type: ButtonType | any; //类型
  icon?: any; //按钮图标
  label: string; //按钮文本
  hideCode?: string; //按钮权限
  clickFn?: Function; //按钮方法
  more?: Boolean; //如果为更多按钮
  dropdownItem?: Array<{ label: string; clickFn: Function }>;
}

// 定义穿过来的props key
interface props {
  // 获取自定义列url
  columnDescriptionUrl: {
    getDynamicColumnsApi: string;
    saveDynamicColumnsApi: string;
  };
  gridOptionsList: Object;
  buttonArr: Array<buttonArrDetails>;
}

// 接受props
const props = withDefaults(defineProps<props>(), {});
// 自定义事件
const emit = defineEmits(["saveCustomColumn"]);
const customGrid = ref();
// 将表格实例暴露出去
const xGrid = ref();
/**
 * 修改自定义弹框显示与隐藏
 */
const controlDialog = () => {
  dialogVisible.value = true;
};
defineExpose({
  xGrid,
  customGrid,
  controlDialog,
});
// ================================================勾选方法=================================================================
/*table选中records*/
const selectionRows = reactive({
  list: [] as any,
});
// 复选框事件(保留翻页选中的数据)
const checkboxChange = ({ checked, records, reserves, row }: any) => {
  // console.log(checked ? "勾选事件" : "取消事件");
  // console.log("当前选中的数据：" + records);
  // console.log("翻页时其他页的数据：" + reserves);
  // console.log("当前选中的数据行：" + row);
  //勾选选中时
  if (checked) {
    //第一次选数据，还未进行翻页时
    if (reserves.length == 0) {
      selectionRows.list = records;
    } else {
      //数据集合，翻页存在已选中的数据时,拼接新选中的数据
      selectionRows.list = [...reserves, ...records];
    }
  } else {
    //取消选中时
    selectionRows.list = selectionRows.list.filter(
      (item: any) => item.id !== row.id
    );
  }
};
//vxe复选框当前页全选中方法(保留翻页选中的数据)：
const selectAllCheckboxChange = ({ checked, records, reserves }: any) => {
  //全选中时
  if (checked) {
    //第一次选数据，还未进行翻页时
    if (reserves.length == 0) {
      selectionRows.list = records;
    } else {
      //数据集合，翻页存在已选中的数据时,拼接新选中的数据
      selectionRows.list = [...reserves, ...records];
    }
  } else {
    //取消全选时,直接将翻页数据赋值，当前页数据不用加上
    selectionRows.list = reserves;
  }
};

// ================================================列自定义==============================================================
// 控制弹框
let dialogVisible = ref(false);
// 控制提示
const showHelpTip = ref(false);
/**
 * 获取动态列(自定义)
 */
const getColumnSetting = () => {
  return getAction(`${props.columnDescriptionUrl.getDynamicColumnsApi}`)
    .then((data: any) => {
      return data.data;
    })
    .catch((err) => {
      console.log("err=>", err);
    });
};
/**
 * 保存动态列(用户自定义)
 */
const saveColumnSetting = (config: any) => {
  return postAction(`${props.columnDescriptionUrl.saveDynamicColumnsApi}`, {
    data: config.body,
  }).then((res: any) => {
    if (res.code == 1000) {
      return ElMessage.success(res.msg);
    }
  });
};
const customColumnConfig = reactive({
  config: {
    class: "sortable-tree-demo",
    border: true,
    keepSource: true,
    showHeaderOverflow: true,
    showOverflow: true,
    height: 320,
    size: "mini",
    editConfig: {
      trigger: "click",
      mode: "cell",
      showStatus: true,
    },
    columns: [
      {
        width: 60,
        align: "center",
        slots: { default: "dragBtn", header: "dragTip" },
      },
      { type: "seq", title: "序号", width: 65, align: "center" },
      {
        field: "dataIndex",
        title: "列编码",
        sortable: true,
        align: "center",
      },
      {
        field: "title",
        title: "列名称",
        sortable: true,
        align: "center",
      },
      {
        field: "width",
        title: "列宽",
        align: "center",
        editRender: { name: "input", props: { placeholder: "请输入列宽" } },
      },
      {
        field: "align",
        title: "对齐方式",
        align: "center",
        editRender: {
          name: "$select",
          enabled: true,
          options: [
            { label: "左对齐", value: "left" },
            { label: "中间对齐", value: "center" },
            { label: "右对齐", value: "right" },
          ],
          props: {},
          // props: { placeholder: "请选择对齐方式" },
        },
      },
      {
        field: "fixed",
        title: "固定方式",
        align: "center",
        editRender: {
          name: "$select",
          options: [
            { label: "无固定", value: "" },
            { label: "左固定", value: "left" },
            { label: "右固定", value: "right" },
          ],
          props: { placeholder: "请选择固定方式" },
        },
      },
      {
        field: "exhibition",
        title: "是否显示",
        align: "center",
        slots: { default: "whetherToHide" },
      },
    ],
    proxyConfig: {
      ajax: {
        // 接收 Promise
        query: (config: any) => {
          return getColumnSetting();
        },
        save: (config: any) => {
          return saveColumnSetting(config);
        },
      },
    },
  } as VxeGridProps,
});
/**
 * 确认自定义列
 */
const saveCustomColumn = () => {
  // 重绘表格
  customGrid.value.commitProxy("save");
  // 触发上层回调 让上层组件重新渲染表格
  //        (因为修改了自定义列后 许多属性都已改变，如表格显示与否、居中方式)
  emit("saveCustomColumn");
  dialogVisible.value = false;
};

onMounted(() => {
  console.log("gridOptionsList", props.gridOptionsList);
});

// ===================================================行拖拽=============================================================
</script>

<style lang="scss">
.vxe-select--panel {
  z-index: 9997 !important;
}
.vxe-input--panel.type--date,
.vxe-input--panel.type--month,
.vxe-input--panel.type--week,
.vxe-input--panel.type--year {
  z-index: 9998 !important;
}
.vxe-table--tooltip-wrapper {
  z-index: 9999 !important;
}

// 行拖拽
.sortable-tree-demo .drag-btn {
  cursor: move;
  font-size: 12px;
}
.sortable-tree-demo .vxe-body--row.sortable-ghost,
.sortable-tree-demo .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
</style>
